﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TienIch.Business;
using TienIch.Utils;
using System.Reflection;
using System.Threading;
using TienIch.Model;
using DevExpress.XtraEditors;

namespace TienIch
{
    public partial class frmRole : FormBase
    {
        int _catID = 0;

        public frmRole()
        {
            InitializeComponent();
            LoadCP();
            loadStaff();
            loadTree();
        }
        void LoadCP()
        {
            DataTable tg = CompanyBO.Instance.FindAll();
            Easy.PopulateCombo(lueCongTy, tg, "Name", "ID", "-- Chọn công ty --");
        }
        private void LoadDepartment(string id)
        {
            try
            {
                DataTable tbl = Easy.Select("Select a.* from Department a with(nolock) where a.Status = 1 and a.IDCompany="+id);
                leDepartment.Properties.DataSource = tbl;
                leDepartment.Properties.DisplayMember = "Name";
                leDepartment.Properties.ValueMember = "ID";
            }
            catch (Exception)
            {
            }

        }

        void loadStaff()
        {
            try
            {
                DataTable tbl = Easy.Select("Select a.* from Users a with(nolock) where a.DepartmentID = " + Easy.ToInt(leDepartment.EditValue));
                grdData.DataSource = tbl;
                grvData.BestFitColumns();
            }
            catch (Exception)
            {
            }
        }

        void loadTree()
        {
            try
            {
                DataTable tbl = Easy.Select("Select ID,Name,ParentID from FormAndFunctionGroup with(nolock) order by Name");

                DataRow row = tbl.NewRow();
                row["ID"] = 0;
                row["Name"] = "--Tất cả các nhóm--";
                tbl.Rows.InsertAt(row, 0);

                treeData.DataSource = tbl;
                treeData.KeyFieldName = "ID";
                treeData.PreviewFieldName = "Name";
                treeData.ParentFieldName = "ParentID";

                treeData.ExpandAll();
                //treeData.CollapseAll();

                //DevExpress.XtraTreeList.Nodes.TreeListNode tNode = treeData.FindNodeByFieldValue("ID", 0);
                //tNode.Expanded = true;

                //DataTable tblRoot = TextUtils.Select("Select a.ID from FormAndFunctionGroup a with(nolock) where ParentID = 0");
                //foreach (DataRow item in tblRoot.Rows)
                //{
                //    DevExpress.XtraTreeList.Nodes.TreeListNode t = treeData.FindNodeByFieldValue("ID", TextUtils.ToInt(item["ID"]));
                //    t.Expanded = true;
                //}
            }
            catch (Exception ex)
            {
                //XtraMessageBox.Show(ex.ToString());
            }
        }

        void loadPermission()
        {
            try
            {
                _catID = Easy.ToInt(treeData.FocusedNode.GetValue(colIDTree));
                if (_catID == 0) return;
                if (Easy.ToInt(grvData.GetFocusedRowCellValue(colID)) == 0) return;

                DataTable Source = Easy.Select("Select * from FormAndFunction WITH(NOLOCK) where FormAndFunctionGroupID = " + _catID );
                //DataTable Source = TextUtils.Select("Select * from vFormAndFunction WITH(NOLOCK)");
                treePermission.DataSource = Source;
                //treePermission.KeyFieldName = "ID";
                //treePermission.PreviewFieldName = "Name";
                //treePermission.ParentFieldName = "FormAndFunctionGroupID";

                for (int i = 0; i < treePermission.Nodes.Count; i++)
                {
                    DataTable dt = Easy.Select("Select * from UserRightDistribution WITH(NOLOCK) where FormAndFunctionID = "
                        + Easy.ToInt(treePermission.GetNodeByVisibleIndex(i).GetValue(colIDPer)) + " and UserID = "
                        + Easy.ToInt(grvData.GetFocusedRowCellValue(colID)));
                    if (dt != null)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            treePermission.GetNodeByVisibleIndex(i).Checked = true;
                        }
                    }
                }
            }
            catch (Exception)
            {

            }
        }

        private void leDepartment_EditValueChanged(object sender, EventArgs e)
        {
            loadStaff();
        }

        private void treeData_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            loadPermission();
        }

        private void grvData_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            loadPermission();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (treePermission.Nodes.Count == 0) return;
            int userID = Easy.ToInt(grvData.GetFocusedRowCellValue(colID));
            if (userID == 0) return;

            for (int i = 0; i < treePermission.Nodes.Count; i++)
            {
                int perID = Easy.ToInt(treePermission.GetNodeByVisibleIndex(i).GetValue(colIDPer));
              
                DataTable dt = Easy.Select("Select * from UserRightDistribution WITH(NOLOCK) where FormAndFunctionID = "
                    + perID + " and UserID = " + userID);
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        if (!treePermission.GetNodeByVisibleIndex(i).Checked)
                        {
                            UserRightDistributionBO.Instance.Delete(Easy.ToInt(dt.Rows[0][0]));
                        }
                    }
                    else
                    {
                        if (treePermission.GetNodeByVisibleIndex(i).Checked)
                        {
                            UserRightDistributionModel model = new UserRightDistributionModel();
                            model.FormAndFunctionID = Easy.ToInt(treePermission.GetNodeByVisibleIndex(i).GetValue(colIDPer));
                            model.UserID = Easy.ToInt(grvData.GetFocusedRowCellValue(colID));
                            UserRightDistributionBO.Instance.Insert(model);
                        }
                    }
                }
            }
            frmLoading frm = new frmLoading(true);
            frm.ShowDialog();
            //XtraMessageBox.Show("Phân quyền thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmRole_Load(object sender, EventArgs e)
        {

        }

        private void lueCongTy_EditValueChanged(object sender, EventArgs e)
        {
            if (lueCongTy.EditValue != null)
            {
                LoadDepartment(lueCongTy.EditValue.ToString());
            }
        }

    }
}
